import type { AxiosRequestConfig } from "axios";
import axios from "axios";
import router from "~/router";
import { useToken, useUserStore, useLogout } from "@/stores";
import { message } from "ant-design-vue";

const instance = axios.create({
  baseURL: "",
  timeout: 60000,
});
const time = 60 * 60 * 1000 * 24; // 前端操作token失效时间

const { token } = useToken();
const { userInfo } = useUserStore();
const { logoutFn } = useLogout();

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    console.log("网络层面成功", config, token, userInfo);
    // 请求拦截，统一设置token

    if (token) {
      const loginTime = Number(localStorage.getItem("loginTime"));
      const curTime = Date.now();
      const dir = curTime - loginTime;
      if (dir > time) {
        // 提示信息
        message.error("用户超时");
        // 退出登录
        logoutFn();
        // 跳转到登录页面
        router.push("/login");
        // 结束请求 报错信息
        return Promise.reject(new Error("登录超时-前端介入"));
      }
      // 请求头设置token和userId
      config.headers["x-token"] = token;
      config.headers["x-user-id"] = userInfo?.ID;
    }
    return config;
  },
  (error) => {
    // console.log("网络层面失败", error);
    message.error(error);
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 如果请求成功成功 2xx 就直接返回 data 中的数据
    return response;
  },
  (error) => {
    // 对响应错误做点什么
    if (!error.response) {
      // 网络错误，response 没有信息
      message.error("网络错误，请换个网络环境");
    } else {
      // 对响应错误做点什么 400 401 404 500 ...
      // 通用错误，通用提示
      message.error(error.response.data.message);
    }
    return Promise.reject(error);
  }
);

export default instance;

export interface ResponseBody<T = any> {
  data: {
    code: string;
    msg: string;
    result: T;
  };
}

export const useGet = <R = any, T = any>(
  url: string,
  params?: T,
  config?: AxiosRequestConfig
): Promise<ResponseBody<R>> => {
  return instance.request({
    url,
    params,
    method: "GET",
    ...config,
  });
};

export const usePost = <R = any, T = any>(
  url: string,
  data?: T,
  config?: AxiosRequestConfig
): Promise<ResponseBody<R>> => {
  return instance.request({
    url,
    data,
    method: "POST",
    ...config,
  });
};

export const usePut = <R = any, T = any>(
  url: string,
  data?: T,
  config?: AxiosRequestConfig
): Promise<ResponseBody<R>> => {
  return instance.request({
    url,
    data,
    method: "PUT",
    ...config,
  });
};

export const useDelete = <R = any, T = any>(
  url: string,
  data?: T,
  config?: AxiosRequestConfig
): Promise<ResponseBody<R>> => {
  return instance.request({
    url,
    data,
    method: "DELETE",
    ...config,
  });
};
